﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft.Json;
using System.Text;
using System.IO;
namespace AUV5.Web.Service
{
    public partial class ServiceAdd : PageBaseService
    {
        //临时文件目录
        private string tempDir = "/UploadFile/Temp/Mobile/" + DateTime.Now.Year.ToString() + "/" + DateTime.Now.Month.ToString() + "/" + DateTime.Now.Day.ToString() + "/";

        //切图所依据的的长和宽
        private int minWidth = Common.CommonDefine.SERVICE_IMAGE_WIDTH;
        private int minHeight = Common.CommonDefine.SERVICE_IMAGE_HEIGHT;


        protected void Page_Load(object sender, EventArgs e)
        {
            string userid = Request["userid"] ?? "";
            string categoryid = Request["categoryid"] ?? "";
            string title = Request["title"] ?? "";
            string description = Request["description"] ?? "";
            int duration = 0;
            try
            {
                duration = int.Parse(Request["duration"]);
            }
            catch
            {
                Response.Write("113");//无效的整型数值
                return;
            }
            string instrcution = Request["instrcution"] ?? "";
            string[] keywords = (Request["keys"]??"").Trim().Replace('，', ',').Split(',');
            HttpFileCollection filelist = Request.Files;

            bool shippable = false;
            try
            {
                shippable = Boolean.Parse(Request["shippable"] ?? "false");
            }
            catch
            {
                Response.Write("114");//无效的布尔值
                return;
            }
            decimal nativeship = 0;
            decimal othership = 0;
            if (shippable)
            {
                if (Request["native"] != null && Request["other"] != null)
                {
                    nativeship = decimal.Parse(Request["native"]??"0");
                    othership = decimal.Parse(Request["other"]??"0");
                }
                else
                {
                    Response.Write("113");//无效的整型数值
                    return;
                }
            }
            //是否有视频
            bool hasvideo = false;
            try
            {
                hasvideo = bool.Parse(Request["hasvideo"] ?? "false");
            }
            catch
            {
                Response.Write("114");//无效的布尔值
                return;
            }

            string serviceid = Request["serviceid"] ?? "";
            string mobilebrand = Request["mobilebrand"] ?? "";
            string mobilemodel = Request["mobilemodel"] ?? "";

            string secretkey = Request["secretkey"] ?? "";

            //if (!IsValidKey(secretkey, userid, categoryid, title, description, duration, instrcution, keywords, shippable, nativeship, othership, hasvideo, filelist, serviceid, mobilebrand, mobilemodel))
            //{
            //    Response.Write("112");//密钥不正确 
            //    return;
            //}

            if (Request["userid"] != null && Request["categoryid"] != null && Request["title"] != null
                && Request["duration"] != null)
            {
                //必填项
                //判断userID的有效性
                if (BLL.UserInfoBLL.Instance.GetDetail(userid) == null)
                {
                    Response.Write("301");//用户编号无效
                    return;
                }

                if (BLL.ServiceCategoryBLL.Instance.GetDetail(categoryid) == null)
                {
                    Response.Write("302");//服务类别编号无效
                    return;
                }
                if (title.Length <= 5 || title.Length > 140)
                {
                    Response.Write("303");//服务标题长度必须在0～140之间
                    return;
                }
                if (BLL.ServiceInfoBLL.Instance.TitleExists(title, serviceid))
                {
                    Response.Write("305");//服务标题已存在 
                    return;
                }
                
                List<string> imglist = new List<string>();
                HttpPostedFile video=null;
                //如果包含视频附件
                if (hasvideo)
                {
                    video = filelist["video"];
                    if (video.ContentLength > 0)
                    {
                        if (true)//检查是否为视频文件
                        {
                            //将视频的上传放到对服务信息添加以后
                        }
                        else
                        {
                            Response.Write("313");//无效视频文件
                            return;
                        }
                    }
                    else
                    {
                        Response.Write("311");//视频附件为空
                        return;
                    }
                }
                //图片附件,最多三个，最少一个
                for (int i = 1; i <= 3; i++)
                {
                    HttpPostedFile imgfile = filelist["image" + i];
                    if (imgfile != null)
                    {
                        if (imgfile.ContentLength > 0)
                        {
                            if (true)//检查是否为图片文件 
                            {
                                Stream stream = imgfile.InputStream;
                                System.Drawing.Image img = System.Drawing.Image.FromStream(stream);
                                if (img.Width < minWidth || img.Height < minHeight)
                                {
                                    Response.Write("319");//图片的长和宽都不得小于固定值
                                    return;
                                }
                                else
                                {
                                    string filename = Common.FileHelper.GetUniqueFileName() + Path.GetExtension(imgfile.FileName);
                                    if (!Directory.Exists(Server.MapPath(tempDir)))
                                    {
                                        Directory.CreateDirectory(Server.MapPath(tempDir));
                                    }
                                    imglist.Add(tempDir + filename);
                                    img.Save(Server.MapPath(tempDir + filename));
                                }
                            }
                            else
                            {
                                Response.Write("314");//无效图片文件 
                                return;
                            }
                        }
                    }
                }

                #region  已注释代码
                //for (int i = 0; i < filelist.Count; i++)
                //{
                //    if (i == 0 && hasvideo)
                //    {
                //        HttpPostedFile video = filelist["video"];
                //        string filename = Common.FileHelper.GetUniqueFileName(Path.GetExtension(video.FileName));
                //        videopath = tempDir + filename;
                //        //将视频的上传放到对服务信息添加以后
                //    }
                //    else
                //    {
                //        Stream stream = filelist[i].InputStream;
                //        System.Drawing.Image img = System.Drawing.Image.FromStream(stream);
                //        if (img.Width < minWidth || img.Height < minHeight)
                //        {
                //            Response.Write("319");//图片的长和宽都不得小于固定值
                //            return;
                //        }
                //        else
                //        {
                //            string filename = Common.FileHelper.GetUniqueFileName(Path.GetExtension(filelist[i].FileName));
                //            imglist.Add(tempDir + filename);
                //            filelist[i].SaveAs(Server.MapPath(tempDir + filename));
                //        }
                //    }
                //}
                #endregion

                if (imglist.Count > 0)
                {

                    //添加或修改服务
                    Model.ServiceInfo service = new Model.ServiceInfo();
                    if (Request["serviceid"] != null)
                    {
                        service = BLL.ServiceInfoBLL.Instance.GetDetail(Request["serviceID"].ToString());
                    }
                    //赋值
                    service.UserID = userid;
                    service.Title = title;
                    service.CategoryID = categoryid;
                    service.Description = description;
                    service.Instruction = instrcution;
                    service.Duration = duration;
                    service.Shippable = shippable;
                    service.NativeShipCharge = nativeship;
                    service.OtherShipCharge = othership;
                    //暂时存储的是IP地址
                    service.ServiceFrom = Request.UserHostAddress;

                    //判断
                    if (Request["serviceid"] == null)
                    {
                        //移动设备添加的服务要记录设备信息
                        service.IsMobileService = true;
                        service.MobileBrand = Request["mobilebrand"] ?? "";
                        service.MobileModel = Request["mobilemodel"] ?? "";
                        service.ExtraFor = null;
                        service.StatusID = (int)Common.Enum.ServiceStatus.Active;
                        //添加  
                        service.ServiceID = Guid.NewGuid().ToString();

                        BLL.ServiceInfoBLL.Instance.Add(service, keywords, imglist);

                        if (hasvideo)
                        {
                            //添加视频
                            AddVideo(service.ServiceID,video);
                        }
                        Response.Write("100");//添加成功

                    }
                    else
                    {
                        //修改（不会修改设备信息）
                        service.UpdateDate = DateTime.Now;
                        BLL.ServiceInfoBLL.Instance.Update(service, keywords, imglist);
                        //如果服务中没有视频，且提交的数据中有视频文件，则
                        if (BLL.ServiceAttachmentBLL.Instance.GetVideo(service.ServiceID) == null && hasvideo)
                        {
                            //添加视频
                            AddVideo(service.ServiceID,video);
                        }

                        Response.Write("101");//修改成功
                    }
                }
                else
                {
                    Response.Write("312");//图片附件为空
                }
            }
            else
            {
                Response.Write("111");
            }
        }

        private bool IsValidKey(string secretkey, string userid, string categoryid, string title, string description, int duration, 
            string instrcution, string[] keywords, bool shippable, decimal nativeship, decimal othership,
            bool hasvideo,HttpFileCollection filelist ,string serviceid, string mobilebrand, string mobilemodel)
        {
            if (secretkey_enable)
            {
                if (string.IsNullOrEmpty(secretkey))
                {
                    return false;
                }
                else
                {
                    string tempstr = public_key + current_day + userid + categoryid + title + description +duration.ToString()+ instrcution + (shippable ? nativeship + othership : 0).ToString();

                    foreach (var key in keywords)
                    {
                        tempstr += key;
                    }

                    if (hasvideo)
                    {
                        if (filelist["video"] != null)
                        {
                            tempstr+=filelist["video"].ContentLength;
                        }
                    }

                    for (int i = 1; i <= 3; i++)
                    {
                        HttpPostedFile imgfile=filelist["image" + i];
                        if ( imgfile!= null)
                        {
                            tempstr += imgfile.ContentLength;
                        }
                    }
                    tempstr += serviceid + mobilebrand + mobilemodel;
                    string finalkey = base.EncryptMD5(tempDir).Substring(6, 22);
                    return finalkey == secretkey;
                }
            }
            else
            {
                return true;
            }
        }

        //添加视频附件
        private void AddVideo(string serviceID,HttpPostedFile video)
        {
            string filename = Common.FileHelper.GetUniqueFileName() + Path.GetExtension(video.FileName);
            string videopath = tempDir + filename;
            //上传视频
            if (!Directory.Exists(Server.MapPath(tempDir)))
            {
                Directory.CreateDirectory(Server.MapPath(tempDir));
            }
            video.SaveAs(Server.MapPath(videopath));
            //添加视频
            BLL.ServiceAttachmentBLL.Instance.AddVideo(serviceID, videopath);
        }
    }
}